package com.mallcai.bigdata.ladon.dpl.mapper.common.provider;

import com.mallcai.bigdata.ladon.dpl.entity.common.Datasource;
import com.mallcai.bigdata.ladon.dpl.mapper.BaseSqlProvider;
import com.mallcai.bigdata.ladon.dpl.mapper.system.provider.UserSqlProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author gst
 * @date 2019-12-30 20:36
 */
public class DatasourceSqlProvider extends BaseSqlProvider<Datasource> {
    public static final String TB_DATASOURCE = "c_datasource";


    @Override
    public String getTableName() {
        return TB_DATASOURCE;
    }

    @Override
    public Map<String, String> getInsertColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("name", "#{name}");
        map.put("type", "#{type}");
        map.put("jdbc_driver", "#{jdbcDriver}");
        map.put("jdbc_url", "#{jdbcUrl}");
        map.put("username", "#{username}");
        map.put("password", "#{password}");
        map.put("timeout", "#{timeout}");
        map.put("test_sql", "#{testSql}");
        return map;
    }

    @Override
    public Map<String, String> getUpdateColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("name", "name");
        map.put("type", "type");
        map.put("jdbcDriver", "jdbc_driver");
        map.put("jdbcUrl", "jdbc_url");
        map.put("username", "username");
        map.put("status", "status");
        map.put("password", "password");
        map.put("timeout", "timeout");
        map.put("testSql", "test_sql");
        return map;
    }

    /**
     * 根据参数查询
     */
    public String getByParams(Map<String, Object> map) {
        Map<String, Object> params = getParams(map);

        StringBuilder sb = new StringBuilder();
        sb.append("tb_d.archive = 0");
        if (params.containsKey("name") && StringUtils.isNotBlank(params.get("name").toString())) {
            sb.append(" and tb_d.name LIKE concat('%',#{params.name},'%')");
        }
        if (params.containsKey("jdbcUrl") && StringUtils.isNotBlank(params.get("jdbcUrl").toString())) {
            sb.append(" and tb_d.jdbc_url = #{params.jdbcUrl}");
        }
        if (params.containsKey("status")) {
            sb.append(" and tb_d.status = #{params.status}");
        }
        if (params.containsKey("type")) {
            sb.append(" and tb_d.type = #{params.type}");
        }
        if (params.containsKey("createdBy")) {
            sb.append(" and tb_d.created_by = #{params.createdBy}");
        }
        return new SQL() {
            {
                SELECT("tb_u.nickname  AS creator, tb_d.*");
                FROM(TB_DATASOURCE + " AS tb_d");
                LEFT_OUTER_JOIN(UserSqlProvider.TB_USER + " tb_u ON tb_u.id = tb_d.created_by");
                WHERE(sb.toString());
            }
        }.toString();
    }
}
